package com.youxin.chat.pay.mq.config;


import com.youxin.common.constant.MqConstant;
import com.youxin.chat.pay.config.PayProperties;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class MqConfig {

    @Resource
    private PayProperties payProperties;

    /**
     * 默认及时消息交换机
     *
     * @return
     */
    @Bean("defaultDirectExchange")
    public DirectExchange defaultDirectExchange() {
        return new DirectExchange("default.direct.exchange", true, false);
    }

    @Bean("defaultTopicExchange")
    public TopicExchange defaultTopicExchange() {
        return new TopicExchange(MqConstant.TOPIC_EXCHANGE, true, false);
    }

    @Bean
    public Queue createUserQueue() {
        return new Queue(MqConstant.CREATE_USER_QUEUE);
    }

    @Bean
    public Queue createPayNotifyQueue() {
        return new Queue(MqConstant.PAY_NOTIFY_QUEUE);
    }

    @Bean
    public Binding concurrentConsumersBinding() {
        return BindingBuilder.bind(createUserQueue()).to(defaultTopicExchange()).with("user.create");
    }

    @Bean
    public Binding notifyQueueBinding() {
        return BindingBuilder.bind(createPayNotifyQueue()).to(defaultDirectExchange()).with(MqConstant.PAY_NOTIFY_QUEUE);
    }


    @Bean
    public Binding redPackTimeOutProcessBinding() {
        return BindingBuilder.bind(processRedPackTimeOutQueue()).to(processExchange()).with(MqConstant.RED_PACK_TIMEOUT_PROCESS_QUEUE_NAME);
    }

    @Bean
    Queue processRedPackTimeOutQueue() {
        return new Queue(MqConstant.RED_PACK_TIMEOUT_PROCESS_QUEUE_NAME);
    }


    @Bean
    public Binding redPackTimeOutSendBinding() {
        return BindingBuilder.bind(sendRedPackTimeOutQueue()).to(delayExchange()).with(MqConstant.RED_PACK_TIMEOUT_SEND_QUEUE_NAME);
    }


    /**
     * 创建delay_queue_per_queue_ttl队列
     *
     * @return
     */
    @Bean
    Queue sendRedPackTimeOutQueue() {
        return QueueBuilder.durable(MqConstant.RED_PACK_TIMEOUT_SEND_QUEUE_NAME)
                .withArgument("x-dead-letter-exchange", MqConstant.PROCESS_EXCHANGE) // DLX
                .withArgument("x-dead-letter-routing-key", MqConstant.RED_PACK_TIMEOUT_PROCESS_QUEUE_NAME) // dead letter携带的routing key
                //.withArgument("x-message-ttl", MqConstant.QUEUE_EXPIRATION) // 设置队列的过期时间
                .withArgument("x-message-ttl", payProperties.getRedPack().getExpireTime()) // 设置队列的过期时间
                .build();
    }


    /**
     * 创建DLX exchangedelayQueuePerMessageTTL
     *
     * @return
     */
    @Bean
    DirectExchange delayExchange() {
        return new DirectExchange(MqConstant.DELAY_EXCHANGE_NAME);
    }

    @Bean
    DirectExchange processExchange() {
        return new DirectExchange(MqConstant.PROCESS_EXCHANGE);
    }

}
